﻿using SeeSharpTools.JY.DSP.Utility;
using SeeSharpTools.JY.DSP.Utility.Filter1D;
using Sunny.UI;
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace SeeSharpTools.Demo
{
    public partial class FormFIRWindow : UIPage
    {
        public FormFIRWindow()
        {
            InitializeComponent();

            uiComboBox_Window.Items.AddRange(Enum.GetNames(typeof(WindowType)));
            uiComboBox_Window.SelectedIndex = 11;
            uiComboBox_BandType.Items.AddRange(Enum.GetNames(typeof(FIRBandType)));
            uiComboBox_BandType.SelectedIndex = 3;
        }

        private void uiButton_Design_Click(object sender, EventArgs e)
        {
            try
            {
                easyChartX_Mag.Miscellaneous.CheckInfinity = true;
                easyChartX_Phase.Miscellaneous.CheckInfinity = true;
                easyChartX_GrpDelay.Miscellaneous.CheckInfinity = true;
                easyChartX_Impulse.Miscellaneous.CheckInfinity = true;

                double sampleRate = uiDoubleUpDown_SampleRate.Value;
                double[] wn = Array.ConvertAll(uiTextBox_Cutoff.Text.Split(','), Convert.ToDouble);
                double[] b = FIRDesign.Window(uiIntegerUpDown_Order.Value, wn, (WindowType)Enum.Parse(typeof(WindowType), uiComboBox_Window.Text),
                    uiDoubleUpDown_Winparam.Value, (FIRBandType)Enum.Parse(typeof(FIRBandType), uiComboBox_BandType.Text), true, sampleRate);
                var (mag, phase, f) = FIRAnalysis.Bode(b, sampleRate, 512);
                easyChartX_Mag.Plot(f, mag);
                easyChartX_Phase.Plot(f, phase);
                var (gd, _) = FIRAnalysis.GroupDelay(b, sampleRate);
                easyChartX_GrpDelay.Plot(f, gd.Select(num => Math.Round(num, 3)).ToArray());
                var (h, t) = FIRAnalysis.ImpulseResponse(b, sampleRate);
                easyChartX_Impulse.Plot(t, h);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}